package com.yc.boot.minio.business;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yc.boot.minio.entity.SysMinio;
import com.yc.boot.minio.service.SysMinioService;
import com.yc.boot.minio.model.FindMinioPage;
import com.yc.boot.minio.utils.CacheUtil;
import com.yc.boot.minio.utils.MinIoUtil;
import com.yc.boot.sys.business.SysUserBusiness;
import com.yc.boot.sys.model.UserInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;

/**
 * @author 杨智杰
 * @since 2021/8/26 13:52
 */
@Slf4j
@Service
public class MinioBusiness {

    @Resource
    private SysUserBusiness sysUserBusiness;

    @Resource
    private SysMinioService sysMinioService;

    /**
     * 上传
     *
     * @return 文件信息
     */
    public SysMinio upload(String bucket, MultipartFile file) {
        try {
            if (CacheUtil.BUCKET_CACHE.contains(bucket)) {
                MinIoUtil.createBucket(bucket);
                CacheUtil.BUCKET_CACHE.add(bucket);
            }
        } catch (Exception e) {
            log.error(e.getMessage());
            return null;
        }
        UserInfo userInfo = sysUserBusiness.getUserInfo();
        String path = DateUtil.format(DateTime.now(), "yyyy/MM/dd/");
        String indexes = makeFileIndexes(file.getOriginalFilename());
        String upload = MinIoUtil.upload(bucket,
                path + StrUtil.BRACKET_START + indexes + StrUtil.BRACKET_END + file.getOriginalFilename(),
                file);
        SysMinio sm = new SysMinio().setUploadBy(ObjectUtil.isNotNull(userInfo) ? userInfo.getId() : null)
                .setUrl(path + StrUtil.BRACKET_START + indexes + StrUtil.BRACKET_END + file.getOriginalFilename())
                .setFileName(file.getOriginalFilename())
                .setIndexes(indexes).setPath(path)
                .setUploadTime(DateUtil.now())
                .setBucket(bucket);
        sysMinioService.save(sm);
        return sm;
    }

    /**
     * 下载
     *
     * @param bucket   所属桶
     * @param fileName 文件名
     */
    public void download(String bucket, String fileName) {
        MinIoUtil.download(bucket, fileName, ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse());
    }

    /**
     * 生成文件索引
     *
     * @param str 文件名
     * @return 文件索引
     */
    private String makeFileIndexes(String str) {
        return SecureUtil.md5(str
                + System.currentTimeMillis()
                + IdUtil.fastUUID());
    }

    /**
     * 分页查询
     *
     * @param param 查询条件
     * @return 分页数据
     */
    public IPage<SysMinio> page(FindMinioPage param) {
        return sysMinioService.page(new Page<>(param.getCurrent(), param.getSize()), new QueryWrapper<SysMinio>().lambda()
                .eq(ObjectUtil.isNotNull(param.getId()), SysMinio::getId, param.getId())
                .like(StrUtil.isNotBlank(param.getPath()), SysMinio::getPath, param.getPath())
                .like(StrUtil.isNotBlank(param.getBucket()), SysMinio::getBucket, param.getBucket())
                .like(StrUtil.isNotBlank(param.getIndexes()), SysMinio::getIndexes, param.getIndexes())
                .like(StrUtil.isNotBlank(param.getFileName()), SysMinio::getFileName, param.getFileName())
                .orderByDesc(SysMinio::getUploadTime)
        );
    }
}
